/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.consumer.transport;

import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.core.invoke.RpcInvokeContext;
import com.lvyh.lightframe.core.invoke.request.Heartbeat;
import com.lvyh.lightframe.core.invoke.response.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    private RpcInvokeContext invokeContext;
    private NettyConnectClient nettyConnectClient;

    public NettyClientHandler(final RpcInvokeContext invokeContext, NettyConnectClient nettyConnectClient) {
        this.invokeContext = invokeContext;
        this.nettyConnectClient = nettyConnectClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse rpcResponse) throws Exception {
        logger.info("[NettyClientHandler] client receive remote result:{}", JSON.toJSONString(rpcResponse));
        invokeContext.setInvokeResponseFuture(rpcResponse.getRequestId(), rpcResponse);
        logger.info("[NettyClientHandler] client refreshe invoke context response future:{}", JSON.toJSONString(rpcResponse));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
        logger.error("[NettyClientHandler] client error:{}", t);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (!(event instanceof IdleStateEvent)) {
            super.userEventTriggered(ctx, event);
        }
        nettyConnectClient.send(Heartbeat.PING_REQ);
        logger.info("[NettyClientHandler] client send heart beat req.");
    }

}
